package com.cuit.qx.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cuit.qx.config.BasicData;
import com.cuit.qx.entity.Product;
import com.cuit.qx.controller.CorrectForecastController;
import com.cuit.qx.entity.RiskWarning;
import com.cuit.qx.mapper.RiskWarningMapper;
import com.cuit.qx.service.ConfigService;
import com.cuit.qx.service.ProductService;
import com.cuit.qx.service.RiskWarningService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cuit.qx.utils.AsposeWordsUtils;
import com.cuit.qx.utils.ReturnData;
import com.cuit.qx.utils.ReturnStateCode;
import lombok.extern.slf4j.Slf4j;
import com.cuit.qx.utils.ReturnData;
import com.cuit.qx.utils.ReturnStateCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.stream.Collectors;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 风险预警表 服务实现类
 * </p>
 *
 * @author lcj
 * @since 2021-11-23
 */
@Service
@Slf4j
public class RiskWarningServiceImpl extends ServiceImpl<RiskWarningMapper, RiskWarning> implements RiskWarningService {

    @Resource
    private ProductService productService;
    @Resource
    private ConfigService configService;

    private static final Logger LOG = LoggerFactory.getLogger(RiskWarningServiceImpl.class);
    @Resource
    private  RiskWarningMapper mapper;

    @Override
    public List<RiskWarning> getRiskWarnin(int pattern, String startDate, String startTime, String time) {

        return mapper.forecastList(pattern, startDate, startTime, time);
    }

    @Override
    public ReturnData updateWarningU(List<RiskWarning> reiskId) {
        try {
            reiskId.forEach(item -> {
                if (null==item.getReiskId()){
                    mapper.updateWarning(item.getTimeValue(),1,item.getId());
                }else {
                    mapper.updateWarning(item.getTimeValue(), item.getReiskId(), item.getId());
                }

            });
            return new ReturnData(ReturnStateCode.SUCCEE.getCode(),ReturnStateCode.SUCCEE.getMsg());
        }catch (Exception e){
            LOG.error("修改风险预警异常",e);
            return new ReturnData(ReturnStateCode.FAILED.getCode(),ReturnStateCode.FAILED.getMsg());
        }

    }

    /**
     * 获取风险预警数据
     *
     * @param pattern   模式
     * @param date      起报日期
     * @param startTime 起报时间
     * @param moment    时效
     * @return
     */
    @Override
    public List<RiskWarning> getList(String pattern, String date, String startTime, String moment,String stationName) {
        LambdaQueryWrapper<RiskWarning> queryWrapper = new LambdaQueryWrapper<>();
        if (StrUtil.isNotBlank(pattern)) {
            queryWrapper.eq(RiskWarning::getPattern, pattern);
        }
        if (StrUtil.isNotBlank(date)) {
            queryWrapper.eq(RiskWarning::getStartDate, date);
        }
        if (StrUtil.isNotBlank(startTime)) {
            queryWrapper.eq(RiskWarning::getStartTime, startTime);
        }
        if (StrUtil.isNotBlank(moment)) {
            queryWrapper.eq(RiskWarning::getTime, moment);
        }
        if (StrUtil.isNotBlank(stationName)){
            queryWrapper.like(RiskWarning::getStaionName,stationName);
        }

        try {
            List<RiskWarning> list = this.baseMapper.selectList(queryWrapper);
            return list;
        }catch (Exception e){
        log.error(e.getMessage());
        }
       return null;
    }

    /**
     * 风险预警产品制作
     *
     * @param pattern
     * @param date
     * @param startTime
     * @param moment
     * @return
     */
    @Override
    public ReturnData makeProduct(String pattern, String date, String startTime, String moment,String stationName, Product product) {
        List<RiskWarning> list = getList(pattern, date, startTime, moment,stationName);
        if (list.isEmpty()) {
            return new ReturnData(ReturnStateCode.FAILED, "查询风险预警数据为空，产品缺失制作数据");
        }
        //风险预警产品 入库
        product.setProductType("1");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String format = sdf.format(new Date());
        product.setCreateTime(format);
        String collect = list.stream().map(e-> e.getStaionName() +"降水"+e.getTimeValue()+"mm")
                .collect(Collectors.joining(";"));
        String s = collect + "以上站点降雨均超过阈值50mm";
        product.setContent(s).setStartDate(date).setStartTime(startTime);

        Map<String, Object> data = configService.getData();
        //获取图片
        String url = "http://"+data.get(BasicData.IMAGESIP)+":"+data.get(BasicData.IMAGESPORT)+"/getProductPath?" +
                "mold=fxyj&pattern="+pattern+"&startTime="+startTime+"&date="+date+"&moment="+moment+"&startDate="+date;
        Integer timeOut = Convert.toInt(data.get(BasicData.TIMEOUT)) * 1000;
        String body = HttpRequest.get(url)
                .timeout(timeOut)
                .execute().body();
        if (body.contains("error")){
            return new ReturnData(ReturnStateCode.FAILED,"图片接口数据异常,制作产品缺失数据");
        }
        body = body.split(";")[0];
        product.setImagesPath(body);

        return productService.getProductFile(product);
    }
}
